﻿using Micro.Core.Configs;
using Micro.Core.Packages;
using Micro.Core.Reflection;
using Micro.Extensions.Refit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// HttpClient   
    /// https://blog.51cto.com/u_15127577/2773851
    /// </summary>
    public class RefitPack : BasePackage
    {
        public override PackLevel Level => PackLevel.Business;
        public override int Order => 100;

        public override IServiceCollection AddServices(IServiceCollection services)
        {
            AddIRefit(services);
            return services;
        }

        public override IServiceCollection AddServicesed(IServiceCollection services)
        {

            RefitOption refitOption = services.GetConfiguration().Get<RefitOption>("Refit");//AppsettingConfigs.get<RefitOption>("Refit");
            if (!refitOption.Enabled)
                return services;
            services.AddRefitServices(refitOption).ExecAddRefitServices();
            return services;
        }


        private void AddIRefit(IServiceCollection services)
        {
            var types = AssemblyManager.AllAssemblies.SelectMany(m => m.GetTypes().Where(t => t.IsInterface && t.IsBaseOn<IRefit>() && t!= typeof(IRefit))).ToArray();
            if (types != null && types.Any())
                services.AddRefitServices(types);
        }
    }
}